package com.base.doublepoint;

public class RotateArray {
    /**
     * 给定一个数组，将数组中的元素向右移动 k 个位置，其中 k 是非负数
     *
     * @param nums
     * @param k
     */
    public void rotate(int[] nums, int k) {
        /**
         * 方法一：复制数组
         */
        if (k > nums.length)
            k = k % nums.length;
        int left = 0, right = nums.length - k;

        int[] new_nums = new int[nums.length];

        for (int i = 0; i < new_nums.length; i++) {
            if (right < new_nums.length) {
                new_nums[i] = nums[right++];
                continue;
            }
            new_nums[i] = nums[left++];
        }
//        for (int i = 0; i < new_nums.length; i++) {
//            nums[i] = new_nums[i];
//        }
        System.arraycopy(new_nums, 0, nums, 0, nums.length);

    }


    //当数组过大，k过大时，此方法超出时间限制
    public void rotate1(int[] nums, int k) {
        if (k > nums.length)
            k = k % nums.length;
        while (k > 0) {
            int tmp = nums[nums.length - 1];
            int n = nums.length - 1;
            while (n > 0) {
                nums[n] = nums[n - 1];
                n--;
            }
            nums[0] = tmp;

            k--;
        }
    }


    public void rotate2(int[] nums, int k) {
        /**
         * 方法二，复制数组优化
         */
        int[] new_nums = new int[nums.length];

        for (int i = 0; i < nums.length; i++) {
            new_nums[(i + k) % nums.length] = nums[i];
        }
        System.arraycopy(new_nums, 0, nums, 0, nums.length);
    }


    public void rotate3(int[] nums, int k) {
        /**
         * 方法三：数组反转。
         *
         */
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start++;
            end--;
        }


    }

    public void rotate4(int[] nums, int k) {
        /**
         * 环状数组
         */
        int n = nums.length;
        k = k % n;

        int count = gcd(n, k);

        for (int start = 0; start < count; start++) {
            int current = start;
            int prev = nums[current];
            do {
                int next = (current + k) % n;
                int tmp = nums[next];
                nums[next] = prev;
                prev = tmp;
                current = next;


            } while (current != start);
        }
        int i=0;

    }

    //求最大公约数
    public int gcd(int x, int y) {
        return y > 0 ? gcd(y, x % y) : x;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};
        int k = 3;
        RotateArray rotateArray = new RotateArray();
        rotateArray.rotate4(nums, k);
    }
}
